<?php

namespace common\helpers;

/**
 * 敏感词过滤扩展类
 *
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class FilterWordHelper {

    /**
     * @todo敏感词过滤，返回结果
     * @paramarray $list 定义敏感词一维数组
     * @paramstring $string 要过滤的内容
     * @returnstring $log 处理结果
     */
    public static function sensitive($list, $string) {
        $stringBefore = str_replace(' ', '', $string);
        $stringBefore = preg_replace('/\s(?=\s)/', '', $stringBefore);

        $count = 0; //违规词的个数
        $sensitiveWord = ''; //违规词
        $stringAfter = $stringBefore; //替换后的内容
        $pattern = "/" . implode("|", $list) . "/i"; //定义正则表达式
        if (preg_match_all($pattern, $stringBefore, $matches)) {
            //匹配到了结果
            $patternList = $matches[0]; //匹配到的数组
            $count = count($patternList);
            $sensitiveWord = implode(',', $patternList); //敏感词数组转字符串
            $replaceArray = array_combine($patternList, array_fill(0, count($patternList), '*')); //把匹配到的数组进行合并，替换使用
            $stringAfter = strtr($stringBefore, $replaceArray); //结果替换
        }
        return [
            'count' => $count,
            'string' => $string,
            'safe' => $stringAfter,
        ];
    }

    //调用方法
    public static function progress($string) {
        //定义敏感词数组
        $list = ['千人计划'];
        return static::sensitive($list, $string);
    }

}
